package com.zyht.wechat.framework.bean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.context.ServletContextAware;

import com.wx.entity.SysWxuser;
import com.wx.service.SysWxuserService;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.website.entity.SystemConfiguration;
import com.zyht.website.service.SystemConfigurationService;
import com.zyht.wechat.framework.constant.ConfigConstants;
import com.zyht.wechat.framework.constant.WechatEnvConstants;
import com.zyht.wechat.framework.env.SystemConfigurationEvn;
import com.zyht.wechat.framework.env.WechatEnv;

public class InitCommonWechatEnvBean implements InitializingBean, ServletContextAware {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private SystemConfigurationService systemConfigurationService;
	
	private SysWxuserService sysWxuserService;

	private ServletContext servletContext;

	@Override
	public void afterPropertiesSet() throws Exception{

		if(null==sysWxuserService){
			logger.error("The bean named 'sysWxuserService' has not been injected.So, The function of getting wxuser can not work well.");
			return;
		}
		
		if(null==systemConfigurationService){
			logger.error("The bean named 'systemConfigurationService' has not been injected.So, The function of getting wxuser can not work well.");
			return;
		}
		Map<String, String> configuration = new HashMap<String, String>();
		List<SystemConfiguration> configurationList = this.systemConfigurationService.getAllConfigurations();
		String wxidKey = PropertiesUtils.getConfig(ConfigConstants.GLOABLE_WXID);
		configurationList.forEach((item)->{
			if(item.getConfigCode().equals(wxidKey)){
				SysWxuser sysWxuser = this.sysWxuserService.selectByWxid(item.getConfigValue());
				if(null!=sysWxuser){
					storeWxuser(sysWxuser);
				}
			}
			configuration.put(item.getConfigKey(), item.getConfigValue());
		});
		storeConfiguration(configuration);
	}

	public void setSysWxuserService(SysWxuserService sysWxuserService){

		this.sysWxuserService = sysWxuserService;
	}
	
	public void setSystemConfigurationService(SystemConfigurationService systemConfigurationService){
	
		this.systemConfigurationService = systemConfigurationService;
	}

	@Override
	public void setServletContext(ServletContext servletContext){

		this.servletContext = servletContext;
	}
	
	private void storeWxuser(SysWxuser sysWxuser){
		this.servletContext.setAttribute(WechatEnvConstants.SERVLETCONTEXT_WXUSER, sysWxuser);
		WechatEnv.storeWxuser(this,sysWxuser);
	}
	
	private void storeConfiguration(Map<String, String> configuration){
		SystemConfigurationEvn.storeConfigurations(this, configuration);
	}
}
